package aa.jx.cartFunction.controller;


import aa.jx.cartFunction.model.*;
import aa.jx.cartFunction.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/order")
public class OrderController {

    private final OrderService orderService;

    @Autowired
    public OrderController(OrderService orderService) {
        this.orderService = orderService;
    }

    @GetMapping("/addresses")
    public ResponseEntity<?> getUserAddresses(@RequestParam("userId") Integer userId) {
        try {
            List<AddressDTO> addresses = orderService.getUserAddresses(userId);
            return ResponseEntity.ok(addresses);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("获取地址失败: " + e.getMessage());
        }
    }

    @PostMapping("/create")
    public ResponseEntity<?> createOrder(@RequestBody OrderRequest orderRequest) {
        try {
            OrderDTO order = orderService.createOrder(
                    orderRequest.getUserId(),
                    orderRequest.getAddressId(),
                    orderRequest.getCartItemIds()
            );
            return ResponseEntity.ok(order);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("创建订单失败: " + e.getMessage());
        }
    }
}
